'use client';

import React, { useState, useEffect } from 'react';
import { Card, Avatar, Row, Col, Input, Select, Button, Form, message, Divider, Typography, DatePicker } from 'antd';
import { UserOutlined, CheckOutlined, EditOutlined, } from '@ant-design/icons';
import { getUserInfo, updateUserInfo } from '@/lib/user';
import Layout from '@/components/Layout';
import dayjs from 'dayjs';

const { Title, Text } = Typography;
const { Option } = Select;

interface UserInfo {
  employeeId: string;
  username: string;
  gender: number | null;
  age: number | null;
  birthday: string | null;
  phoneNumber: string | null;
  email: string | null;
  department: number;
  deptName: string;
  deptType: number;
  position: string;
  status: number;
  role: string;
  avatarUrl?: string;
}

interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}

const STATUS_MAP: { [key: number]: string } = {
  0: '试用期员工',
  1: '正式员工',
  2: '离职'
};

const DEPT_TYPE_MAP: { [key: number]: string } = {
  1: '职能部门',
  2: '学院',
  3: '其它部门'
};

const ProfilePage = () => {
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [originalUserInfo, setOriginalUserInfo] = useState<UserInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [changedFields, setChangedFields] = useState<string[]>([]);
  const [isPhoneEditable, setIsPhoneEditable] = useState(false);
  const [isEmailEditable, setIsEmailEditable] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchUserInfo();
  }, []);

  const fetchUserInfo = async () => {
    setLoading(true);
    try {
      const response = await getUserInfo() as { data: ApiResponse<UserInfo> };
      if (response.data && response.data.code === 1) {
        const userData = response.data.data;
        console.log("员工信息:", userData);
        setUserInfo(userData);
        setOriginalUserInfo(userData);
        form.setFieldsValue({
          ...userData,
          birthday: userData.birthday ? dayjs(userData.birthday) : null,
          status: STATUS_MAP[userData.status], // 直接设置状态文本
          deptType: DEPT_TYPE_MAP[userData.deptType] // 直接设置部门类型文本
        });
      } else {
        message.error('获取用户信息失败: ' + response.data.message);
      }
    } catch (error) {
      console.error('获取用户信息时发生错误:', error);
      message.error('获取用户信息时发生错误');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const submitData = {
        gender: String(values.gender || 0),  // 将 gender 转换为字符串
        age: values.age || 0,
        birthday: values.birthday,
        phoneNumber: values.phoneNumber || '',
        email: values.email || ''
      };

      console.log("提交的数据:", JSON.stringify(submitData, null, 2));
      const response = await updateUserInfo(submitData);

      if (response.data && response.data.code === 1) {
        message.success('个人信息保存成功');
      } else {
        throw new Error(response.data?.msg || '保存失败');
      }
    } catch (error) {
      console.error('保存失败:', error);
      message.error('保存失败：' + (error instanceof Error ? error.message : '未知错误'));
    }
  };

  const fieldChanged = (changedValues: Record<string, any>, allValues: Record<string, any>) => {
    const changedFieldNames = Object.keys(changedValues);
    setChangedFields(prev => Array.from(new Set([...prev, ...changedFieldNames])));
  };

  const cancelChanges = () => {
    if (originalUserInfo) {
      form.setFieldsValue({
        ...originalUserInfo,
        birthday: originalUserInfo.birthday ? dayjs(originalUserInfo.birthday) : null
      });
    }
    setChangedFields([]);
    setIsPhoneEditable(false);
    setIsEmailEditable(false);
  };

  const togglePhoneEdit = () => {
    if (isPhoneEditable) {
      handleSubmit();
    } else {
      setIsPhoneEditable(true);
      setChangedFields(prev => [...prev, 'phoneNumber']);
    }
  };

  const toggleEmailEdit = () => {
    if (isEmailEditable) {
      handleSubmit();
    } else {
      setIsEmailEditable(true);
      setChangedFields(prev => [...prev, 'email']);
    }
  };

  return (
    <Layout>
      <div style={{ padding: '20px', backgroundColor: '#e3f2fd', minHeight: '100vh', borderRadius: '20px' }}>
        <Row justify="center">
          <Col xs={24} md={16} lg={12}>
            <Card loading={loading} style={{ borderRadius: '15px' }}>
              <div style={{ textAlign: 'center', padding: '20px 0', backgroundColor: '#f5f5f5' }}>
                <Avatar size={100} icon={<UserOutlined />} src={userInfo?.avatarUrl} style={{ marginBottom: '16px', border: '4px solid white', boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }} />
                <Title level={4}>{userInfo?.username}</Title>
                <Text type="secondary">{userInfo?.role}</Text>
              </div>
              <Divider />
              <Form form={form} onValuesChange={fieldChanged} onFinish={handleSubmit}>
                <Row gutter={16}>
                  <Col span={12}>
                    <Form.Item name="employeeId" label="工号">
                      <Input readOnly />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item name="username" label="姓名">
                      <Input readOnly />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item name="department" label="部门ID">
                      <Input readOnly />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item name="deptName" label="部门名称">
                      <Input readOnly />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item name="position" label="职位">
                      <Input readOnly />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item name="status" label="任职状态">
                      <Input readOnly value={STATUS_MAP[userInfo?.status || 0]} />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item name="deptType" label="部门类型">
                      <Input readOnly value={DEPT_TYPE_MAP[userInfo?.deptType || 1]} />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item name="gender" label="性别">
                      <Select>
                        <Option value={1}>男</Option>
                        <Option value={2}>女</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item name="age" label="年龄">
                      <Input type="number" min={0} max={150} />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item 
                      name="birthday" 
                      label="出生日期"
                      rules={[
                        { required: true, message: '请选择出生日期' }
                      ]}
                    >
                      <DatePicker 
                        style={{ width: '100%' }}
                        format="YYYY-MM-DD"
                      />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item 
                      name="phoneNumber" 
                      label="手机号"
                    >
                      <Input 
                        readOnly={!isPhoneEditable}
                        suffix={
                          <Button 
                            type="link" 
                            icon={isPhoneEditable ? <CheckOutlined /> : <EditOutlined />}
                            onClick={togglePhoneEdit}
                          />
                        }
                      />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item 
                      name="email" 
                      label="邮箱"
                    >
                      <Input 
                        readOnly={!isEmailEditable}
                        suffix={
                          <Button 
                            type="link" 
                            icon={isEmailEditable ? <CheckOutlined /> : <EditOutlined />}
                            onClick={toggleEmailEdit}
                          />
                        }
                      />
                    </Form.Item>
                  </Col>
                </Row>
                <Row justify="center" style={{ marginTop: '24px' }}>
                  <Col>
                    <Button type="primary" htmlType="submit" loading={isLoading} style={{ marginRight: '8px' }}>保存</Button>
                    {(changedFields.length > 0 || isPhoneEditable || isEmailEditable) && (
                      <Button onClick={cancelChanges}>取消</Button>
                    )}
                  </Col>
                </Row>
              </Form>
            </Card>
          </Col>
        </Row>
      </div>
    </Layout>
  );
};

export default ProfilePage;